package dao

import (
	"aglaia/global"
	"aglaia/internal/model"
	"fmt"
)

func (d *Dao) GetAuth(appKey, appSecret, loginIp string) (auth model.Auth, surplus int, err error) {
	auth = model.Auth{AppKey: appKey, AppSecret: appSecret}
	authRecord := model.AuthRecord{
		AuthId:      auth.Id,
		LastLoginIp: loginIp,
	}

	tx := d.engine.Begin()
	if err := auth.Get(tx); err != nil {
		global.Logger.Errorf("auth.Get err: %v\n", err)
		surplus, err := authRecord.Create(tx)
		if err != nil {
			return model.Auth{}, surplus, err
		}

		return model.Auth{}, surplus, fmt.Errorf("login failed %d second", surplus)
	}

	authRecord.IsSuccess = true
	surplus, err = authRecord.Create(tx)
	if err != nil {
		return model.Auth{}, surplus, err
	}

	return auth, surplus, nil
}
